package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import pojo.Aluno;
import pojo.Turma;


public class DAOBusca <T> {
	EntityManagerFactory emf = Persistence.createEntityManagerFactory("JUniversity");
	EntityManager em = emf.createEntityManager();
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> busca(Class entity) throws PersistenceException {
		Query q = em.createQuery("SELECT a FROM " + entity.getSimpleName() + " a");
		return q.getResultList();
	}
	
	public List<Aluno> buscaLike(String parametro) throws PersistenceException{
		Query query = em.createQuery("select a from Aluno a where upper(a.nome) like upper(:parametro)");
		query.setParameter("parametro", "%"+parametro+"%");
		return query.getResultList(); 
	}
	
//	public List<Turma> buscaTurma(String parametro) throws PersistenceException{
//		Query query = em.createQuery("select t from Turma t where upper(t.nome) like upper(:parametro)");
//		query.setParameter("parametro", "%"+parametro+"%");
//		return query.getResultList(); 
//		
//		//select disciplina_id from Turma where descricao = 'i51';
//	}
	
	public List<Turma> buscaTurma(Long codTurma) throws PersistenceException{
		int valor =  codTurma.intValue();
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery q = cb.createQuery();
		Root<Turma> from = q.from(Turma.class);
		CriteriaQuery<Turma> select = q.select(from);
		Predicate p = cb.equal(from.get("turma").get("id"), valor);
		TypedQuery<Turma> typedQuery = em.createQuery(select.where(p));  
        return typedQuery.getResultList(); 
	}
	

	public List<T> ordenarLista(int modoOrdenar,Class c,String atributo) throws PersistenceException{
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<T> q = cb.createQuery(c);
		Root<T> from = q.from(c);
		q.select(from);
		if(modoOrdenar==1){//crescente
			q.orderBy(cb.asc(from.get(atributo)));
		}
		else{//decrescente
			q.orderBy(cb.desc(from.get(atributo)));
		}
		TypedQuery<T> typed = em.createQuery(q);
		return typed.getResultList(); 
	}

}
